package com.soujiayi.store;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String NAME = "soujiayi";
	private static final int VERSION = 1;
	private static final String TB_SEARCHHISTORY = "searchhistory";

	public DatabaseHelper(Context context) {
		super(context, NAME, null, VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("CREATE TABLE IF NOT EXISTS "
				+ TB_SEARCHHISTORY
				+ " (id integer primary key autoincrement, inputStr varchar(100), searchdate datetime default (datetime('now','localtime')))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		// TODO Auto-generated method stub
		//db.execSQL("alter table "+TB_SEARCHHISTORY+" add column searchdate datetime default datetime('now','localtime')");
	}

	public void insertSearchHistory(String input) {
		SQLiteDatabase db = getWritableDatabase();
	//	Cursor cursor = db.rawQuery("select count(inputStr) from "
	//			+ TB_SEARCHHISTORY+" where inputStr='"+input+"'", null);	
		
	//	if(!cursor.moveToNext())
	//	 {
			ContentValues cv = new ContentValues();
			cv.put("inputStr", input);
			db.insert(TB_SEARCHHISTORY, null, cv);
	//		cursor.close();
			db.close();
//		}else{
//			updateSearchHistory(input);
//		}
		
	}

	public void removeAllSearchHistory() {
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("delete from " + TB_SEARCHHISTORY);
		db.close();
	}
	
	public void updateSearchHistory(String input){
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("update " + TB_SEARCHHISTORY+" set searchdate=datetime('now','localtime') where inputStr='"+input+"'");
		db.close();
	}

	public List<String> getAllSearchHistory() {
		List<String> list = new ArrayList<String>();
		SQLiteDatabase db = getWritableDatabase();
		Cursor cursor = db.rawQuery("select inputStr from " + TB_SEARCHHISTORY
				+ " order by searchdate desc", null);
		while (cursor.moveToNext()) {
			list.add(cursor.getString(0));
		}
		cursor.close();
		db.close();
		return list;
	}
}
